package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import user.UserBean;

public class UserController extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	public void process ( HttpServletRequest request, HttpServletResponse response ) {
		ServletContext context;
		RequestDispatcher dispatcher;
		
		String error = null;
						
		context = getServletContext();
			

		if(request.getParameterNames() != null)
        {		
			
			String username = request.getParameterValues("username")[0];
			String password = request.getParameterValues("password")[0];
			String confirmPassword = request.getParameterValues("confPassword")[0];
			String fullname = request.getParameterValues("fullname")[0];
			String location = request.getParameterValues("location")[0];
			boolean isAdmin = Boolean.getBoolean(request.getParameterValues("admin")[0]);
			boolean isInactive = Boolean.getBoolean(request.getParameterValues("inactive")[0]);
				
			if(username != null && password != null && fullname != null && confirmPassword != null)
			{
				if(password.equals(confirmPassword))
				{
					UserBean user = new UserBean();
					user.addUser(username, password, fullname, location, isAdmin, isInactive);
				}
				else
				{
					error = "Password and confirmation does not match";
				}
			}
			else 
			{
				error = "Benutzer konnte nicht erstellt werden.";
			}
		}
		else 
		{
			error = "Benutzer konnte nicht erstellt werden.";
		}				
		
		if (error != null && !error.isEmpty())
			request.setAttribute("errorMessage", error);
		
		dispatcher = context.getRequestDispatcher("/user.jsp");
				
		try {
			dispatcher.forward(request, response);
		} 
		catch (ServletException e) {
			e.printStackTrace();
			
		} 
		catch (IOException e) {
			e.printStackTrace();
		}	

	}

	public void doGet ( HttpServletRequest request, HttpServletResponse response ) {
		process(request, response);
	}
	
	public void doPost ( HttpServletRequest request, HttpServletResponse response ) {
		process(request, response);
	}
}


